package psico_test.appEjecutar;

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.File;
import java.util.HashMap;
import java.util.Vector;

import javax.realtime.RealtimeThread;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;

import com.easynth.lookandfeel.EaSynthLookAndFeel;

import psico_test.psicoTest;
import psico_test.appEjecutar.gui.ventanaEjecutar;
import psico_test.utils.bd.BDManager;
import psico_test.utils.file.FileManager;

public class appEjecutar extends RealtimeThread
{
	private psicoTest psicoTest;
	
	private ventanaEjecutar gui;
	public ventanaEjecutar getGui() {return gui;}

	private Thread threadGui;
	
	private ManagerEjecucion managerEjecucion;
	public ManagerEjecucion getManagerEjecucion(){return managerEjecucion;}

	private Vector experimentos;
	
	public appEjecutar(psicoTest psicoTest)
	{
		//Asignacion de variables
		this.psicoTest = psicoTest;
		experimentos = new Vector();
		gui = new ventanaEjecutar(this);
		try
		{
			UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
			SwingUtilities.updateComponentTreeUI(gui);
			System.out.println("Apariencia cambiada correctamente");
		}catch(Exception e)
		{System.out.println("Error al cargar el Look And Feel");}
	}
	
	//Arranca la sub-aplicacion
	public void run()
	{	
		threadGui = new Thread(gui);
		threadGui.start();
	}
	
	public void salir()
	{
		threadGui.interrupt();
		try
		{
			UIManager.setLookAndFeel(new EaSynthLookAndFeel());
			System.out.println("Apariencia reestablecida correctamente");
		}catch(Exception e)
		{System.out.println("Recuperando apariencia original");}
		psicoTest.stopAppEjecutar();
	}

	public Object añadirExperimento() 
	{
		File f = FileManager.getInstance().abrirArchivo();
		experimentos.add(f);
		return f;
	}

	public void borrarExperimento(Object aux)
	{
		experimentos.remove(aux);
	}
	
	public void iniciarExperimento(Object experimento)
	{
		if((experimentos == null) || experimentos.size()<1)
			return;
		JOptionPane.showMessageDialog(null,"El experimento empezará en 3 segundos aproximadamente");
		
		managerEjecucion = new ManagerEjecucion(this,(File)experimento);
		managerEjecucion.start();
		System.out.println("Experimento inicializado");
	}
	
	public void pararExperimento()
	{
		if((managerEjecucion != null) && (!managerEjecucion.isAlive()))
		{
			managerEjecucion.stop();
		}
		System.out.println("Experimento detenido");
	}
	
	public static void main(String[]args)
	{
		appEjecutar ae = new appEjecutar(null);
		ae.start();
	}
}
